<template>
    <section class="transaction-wrapper">
      <el-form :inline="true" :model="param" label-width="0" class="transaction-wrapper_search">
        <el-form-item label="">
          <el-select v-model="param.relatedCompanyCode" placeholder="请选择销售主体" @change="getRelatedInfo" clearable>
            <el-option
              v-for="(item, index) in salesList"
              :key="index"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="">
        <el-select v-model="param.businessCompanyCode" placeholder="请选择采购主体" @change="getBusinessInfo" clearable>
          <el-option
            v-for="(item, index) in purchaseList"
            :key="index"
            :label="item.name"
            :value="item.code">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="">
          <el-input v-model="param.rate" placeholder="请输入折扣率" @keyup.enter.native="onCreate" clearable></el-input>
        </el-form-item>
        <el-button type="primary" @click="onCreate">添加</el-button>
      </el-form>
      <el-button type="primary" class="mtb15">导出配置</el-button>
      <el-button type="primary" class="mtb15" @click="showDialog = true">导入配置</el-button>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column prop="relatedCompanyName" label="销售主体"></el-table-column>
        <el-table-column prop="businessCompanyName" label="采购主体"></el-table-column>
        <el-table-column prop="rate" label="折扣率(%)">
          <template slot-scope="scope">
            <div v-if="!flagList[scope.$index]">{{ scope.row.rate }} &nbsp;&nbsp;<i class="el-icon-edit" @click="editRate(scope.$index)"></i></div>
            <div v-else><el-input v-model="scope.row.rate" :ref="scope.$index" @blur="modifyRate(scope.$index)"></el-input></div>
          </template>
        </el-table-column>
      </el-table>
    <!-- 分页 -->
    <el-pagination
      align="right"
      style="padding-top: 20px;margin-bottom:100px;"
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageData.currentPage"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageData.pageSize"
      :total="pageData.total"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>
    <import-dialog :showDialog="showDialog" @close="closeDialog" @save="saveDialog"></import-dialog>
</section>
</template>

<script>
import SeContent from '@/components/se-content.vue'
import SeForm from '@/components/se-form.vue'
import NbTable from '@/components/nb-table.vue'
// import {removeEmptyParams} from '@/common/utils'
import importDialog from './importDialog.vue'

const DEFAULT_DATA = {
  relatedCompanyCode: '',
  relatedCompanyNo: '',
  relatedCompanyName: '',
  businessCompanyCode: '',
  businessCompanyNo: '',
  businessCompanyName: '',
  rate: ''
}

export default {
  components: {
    SeContent,
    SeForm,
    NbTable,
    importDialog
  },
  data () {
    return {
      param: Object.assign({}, DEFAULT_DATA),
      pageData: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      salesList: [],
      purchaseList: [],
      tableData: [],
      flagList: [],
      historyRate: '',
      showDialog: false
    }
  },
  mounted () {
    let p1 = this.getSalesConfig()
    let p2 = this.getPurchaseConfig()
    const p = Promise.all([p1, p2])
    p.then(() => {
      this.getList()
    })
  },
  methods: {
    editRate (index) {
      this.historyRate = this.tableData[index].rate
      this.flagList.splice(index, 1, true)
      this.$nextTick(() => {
        this.$refs[index].focus()
      })
    },
    modifyRate (index) {
      this.flagList.splice(index, 1, false)
      if (!this.tableData[index].rate) {
        this.$message.success('空了')
        this.tableData[index] = Object.assign(this.tableData[index], {
          rate: this.historyRate
        })
        return
      }
      let rate = Number(this.tableData[index].rate)
      if (!rate) {
        this.$message.error('只能输入数字')
        this.tableData[index] = Object.assign(this.tableData[index], {
          rate: this.historyRate
        })
        return
      }
      if (rate > 100 || rate < 0) {
        this.$message.error('折扣率只能在1-100之间')
        this.tableData[index] = Object.assign(this.tableData[index], {
          rate: this.historyRate
        })
        return
      }
      if (this.tableData[index].rate !== this.historyRate) {
        let param = {
          id: this.tableData[index].id,
          rate: Number(this.tableData[index].rate)
        }
        console.log('param: ', param)
        this.$http.post(`/${this.$const.PREFIX.MAINDATA}/internalprice/update`, param).then(res => {
          if (res.result) {
            this.$message.success('修改成功')
          } else {
            this.$message.error('修改失败')
            this.tableData[index] = Object.assign(this.tableData[index], {
              rate: this.historyRate
            })
          }
          console.log('res: ', res)
        }).catch(() => {})
        // 修改失败 就改回去
        // setTimeout(() => {
        //   this.tableData[index] = Object.assign(this.tableData[index], {
        //     rate: this.historyRate
        //   })
        // }, 5000)
        // 请求接口
      } else {
        this.$message.success('没有修改')
      }
    },
    getSalesConfig () {
      let p1 = this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/company/findCompanyList`, {
        isProcuringEntity: false
      }).then(res => {
        this.salesList = res.data
      }).catch(() => {

      })
      return p1
    },
    getPurchaseConfig () {
      let p2 = this.$http.post(`/${this.$const.PREFIX.AUTHORITY}/company/findCompanyList`, {
        isProcuringEntity: true
      }).then(res => {
        this.purchaseList = res.data
      }).catch(() => {

      })
      return p2
    },
    getRelatedInfo () {
      if (this.param.relatedCompanyCode) {
        let index = this.salesList.findIndex(item => item.code === this.param.relatedCompanyCode)
        if (index !== -1) {
          this.param.relatedCompanyNo = this.salesList[index].companyNo || ''
          this.param.relatedCompanyName = this.salesList[index].name || ''
        }
      } else {
        this.param.relatedCompanyNo = ''
        this.param.relatedCompanyName = ''
      }
    },
    getBusinessInfo () {
      if (this.param.businessCompanyCode) {
        let index = this.purchaseList.findIndex(item => item.code === this.param.businessCompanyCode)
        if (index !== -1) {
          this.param.businessCompanyNo = this.purchaseList[index].companyNo || ''
          this.param.businessCompanyName = this.purchaseList[index].name || ''
        }
      } else {
        this.param.businessCompanyNo = ''
        this.param.businessCompanyName = ''
      }
    },
    async getList () {
      let {data} = await this.$http.post(`/${this.$const.PREFIX.MAINDATA}/internalprice/page`, {
        current: this.pageData.currentPage,
        size: this.pageData.pageSize
      })
      this.tableData = data.records
      this.flagList = this.tableData.map(() => false)
      this.pageData.total = data.total
    },
    onCreate () {
      if (!this.param.relatedCompanyCode || !this.param.businessCompanyCode || !this.param.rate) {
        this.$message.warning('请填写完整信息再添加! ')
        return
      }
      if (this.param.relatedCompanyCode === this.param.businessCompanyCode) {
        this.$message.warning('主体相同，不能添加配置! ')
        return
      }
      this.$http.post(`/${this.$const.PREFIX.MAINDATA}/internalprice/save`, this.param).then(res => {
        this.$message.success('添加成功！')
        this.getList()
        this.param = Object.assign({}, DEFAULT_DATA)
      }).catch(() => {

      })
    },
    delQueryModel () {},
    sizeChangeHandle (val) {
      this.pageData.pageSize = val
      this.getList()
    },
    currentChangeHandle (val) {
      this.pageData.currentPage = val
      this.getList()
    },
    closeDialog () {
      this.$message.success('取消弹窗')
      this.showDialog = false
    },
    saveDialog () {
      this.$message.success('保存弹窗')
      this.showDialog = false
    }
  }
}
</script>
<style lang="scss">
  .transaction-wrapper{
    &_search{
      background: white;
      padding: 20px 0 0 20px;
    }
  }
  .mtb15{
    margin: 15px 0;
  }
</style>

